﻿//using System;
using System.Collections.Generic;

using System.Text;
using Microsoft.Win32;
using System;

namespace MSL.Utility.API
{
    /// <summary>
    /// 注册表操作类
    /// </summary>
    public class Regedit
    {
        #region 变量/属性

        private RegistryKey _hklm;
        private RegistryKey _software;
        private RegistryKey _aimdir;
        private String _nodeName;

        /// <summary>
        /// 节点名
        /// </summary>
        public String NodeName
        {
            get
            {
                if (String.IsNullOrEmpty(this._nodeName))
                {
                    this._nodeName = "lin.com";
                }
                return _nodeName;
            }
            set { _nodeName = value; }
        }
        #endregion

        #region 公共方法

        /// <summary>
        /// 读取指定名称的注册表的值
        /// </summary>
        /// <param name="name">注册表值</param>
        /// <returns></returns>
        public string Read(string name)
        {
            OnInit();
            return this._aimdir.GetValue(name).ToString();
        }

        /// <summary>
        /// 注册表中写数据 
        /// </summary>
        /// <param name="name">注册表</param>
        /// <param name="tovalue">值</param>
        public void Write(string name, string tovalue)
        {
            OnInit();
            this._aimdir.SetValue(name, tovalue);
        }

        /// <summary>
        /// .删除注册表中指定的注册表项
        /// </summary>
        /// <param name="name">注册表</param>
        public void Delete(string name)
        {
            OnInit();
            string[] aimnames = _aimdir.GetSubKeyNames();
            foreach (string aimKey in aimnames)
            {
                if (aimKey == name)
                    this._aimdir.DeleteSubKeyTree(name);
            }
        }

        /// <summary>
        /// 判断指定注册表项是否存在
        /// </summary>
        /// <param name="name">注册表</param>
        /// <returns></returns>
        public bool Exist(string name)
        {
            OnInit();
            bool exit = false;
            string[] subkeyNames = this._aimdir.GetSubKeyNames();
            foreach (string keyName in subkeyNames)
            {
                if (keyName == name)
                {
                    exit = true;
                    return exit;
                }
            }
            return exit;
        }
        #endregion

        #region 私有

        /// <summary>
        /// 初始化
        /// </summary>
        private void OnInit()
        {
            this._hklm = Registry.LocalMachine;
            this._software = _hklm.OpenSubKey("SOFTWARE", true);
            this._aimdir = _software.CreateSubKey(this._nodeName);
        }
        #endregion
    }
}
